import React from 'react'
import {
  BaseListPage,
  IBaseListPageState,
  IBaseListPageProps,
  columnRenders,
  http,
  UdTable,
  UdDrawer,
  uaaApp,
  IUdFormItem,
  IUdColumn,
} from '@/lib'
import { Spin, message, Button, Tooltip } from 'antd'
import { downBlobFileXlsx } from '@/utils/methods'
import ViewAreaModal from './components/ViewAreaModal'
import ViewCustomerModal from './components/ViewCustomerModal'
import PlanTable from './components/PlanTable'
import ImportRecordModal from './components/ImportRecordModal'
import comApis from '@/apis'
import quotaApis from '@/apis/AboutQuota'
import UdSelect from '@/components/UdFormControls/UdSelect'
import udMainStore from '@/store/UdMain'
import ImportExcel from './components/ImportExcel'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import _ from 'lodash'
import BatchImportExcel from './components/BatchImportExcel'

const CREATE_NEW_PLAN = 'quota_Import_newplan'
const EXPORT_QUOTA_LIST = 'quota_Import_export'
const IMPORT_QUPTA_LOGS = 'quota_Import_importlog'
const EDIT_PLAN = 'quota_Import_editplan'
const quota_Import_lookItemCustom = 'quota_Import_lookItemCustom'
const quota_Import_lookItemArea = 'quota_Import_lookItemArea'
const quota_Import_lookCustom = 'quota_Import_lookItemArea'
const quota_Import_lookArea = 'quota_Import_lookItemArea'
const quota_Import_importStandard = 'quota_Import_importStandard'
const quota_Import_importActual = 'quota_Import_importActual'
const quota_Import_importAdjust = 'quota_Import_importAdjust'
const quota_Import_batchImportActual = 'quota_Import_batchImportActual'
export default class QuotaImportList extends BaseListPage<QuotaImportListProps, QuotaImportListState> {
  private brandList = udMainStore.brandList
  protected useConditionsField = true
  constructor(props) {
    super(props)
    this.state = {
      fileList: [],
      dataSource: [],
      title: '配额导入',
      selectData: {},
      rowKey: 'id',
      queryApi: quotaApis.getQuotaImportList,
      method: 'POST',
      conditions: [
        {
          label: '品牌公司',
          id: 'brandCode',
          initialValue: this.brandList[0].value,
          render: (
            <UdSelect
              showSearch
              allowClear={false}
              options={this.brandList}
              onChange={value => {
                this.getProdBarList(value)
              }}
            />
          ),
        },
        {
          label: '考核年度',
          id: 'stageYear',
          render: () => <UdSelect options={this.state.stageYearList} showSearch={true} optionFilterProp="children" />,
        },
        {
          id: 'prodBarcode',
          label: '配额品项',
          render: () => <UdSelect showSearch options={this.state.prodBarCodeList} />,
        },
      ],
      columns: [
        { title: '品牌公司', key: 'brandName', dataIndex: 'brandName', minWidth: '160px' },
        { title: '配额品项', key: 'prodBarname', dataIndex: 'prodBarname', minWidth: '130px' },
        {
          title: '片区',
          dataIndex: 'belongAreaName',
          key: 'belongAreaName',
          width: 180,
          render: (text, record) => {
            return (
              <Tooltip title={record.belongAreaName}>
                <div style={{ width: '180px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.belongAreaName}
                </div>
              </Tooltip>
            )
          },
        },
        { title: '考核年度', key: 'stageYear', dataIndex: 'stageYear', minWidth: '60px' },
        {
          title: '年度标准配额',
          key: 'standardQuotaSumTitle',
          dataIndex: 'standardQuotaSumTitle',
          align: 'center',
          children: [
            {
              title: '计划内',
              align: 'center',
              dataIndex: 'standardQuotaSum',
              key: 'standardQuotaSum',
              width: 80,
            },
            {
              title: '计划外',
              align: 'center',
              dataIndex: 'standardQuotaSumWay',
              key: 'standardQuotaSumWay',
              width: 80,
            },
          ],
        },
        {
          title: '年度实际配额',
          key: 'actualQuotaSumTitle',
          dataIndex: 'actualQuotaSumTitle',
          align: 'center',
          children: [
            {
              title: '计划内',
              align: 'center',
              dataIndex: 'actualQuotaSum',
              key: 'actualQuotaSum',
              width: 90,
            },
            {
              title: '计划外',
              align: 'center',
              dataIndex: 'actualQuotaSumWay',
              key: 'actualQuotaSumWay',
              width: 90,
            },
          ],
        },
        {
          title: '年度剩余配额',
          key: 'residualQuotaSumTitle',
          dataIndex: 'residualQuotaSumTitle',
          align: 'center',
          children: [
            {
              title: '计划内',
              align: 'center',
              dataIndex: 'residualQuotaSum',
              key: 'residualQuotaSum',
              width: 90,
            },
            {
              title: '计划外',
              align: 'center',
              dataIndex: 'residualQuotaSumWay',
              key: 'residualQuotaSumWay',
              width: 90,
            },
          ],
        },
        {
          title: '操作',
          width: '300px',
          render: columnRenders.operate(
            [
              {
                title: '导入标准配额',
                auth: quota_Import_importStandard,
                show: (text: any, record: any, index: number) => {
                  if (
                    ['GS100283', 'GS100300', 'GS100318', 'GS100276', 'GS100277', 'GS100285', 'BM100663'].includes(
                      record.brandCode
                    )
                  ) {
                    return true
                  } else {
                    if (record.isIm === 1) {
                      return false
                    }
                  }
                },
                action: (text: any, record: any) =>
                  this.showImportExcel({ record, modifyType: 'QUOTACHANGE', name: '客户标准配额模板' }),
              },
              {
                title: '编辑阶段计划',
                auth: EDIT_PLAN,
                action: (text: any, record: any) => this.showAddPlanModal(record),
              },
              {
                title: '查看客户',
                auth: quota_Import_lookItemCustom,
                action: (text: any, record: any) => this.openModalViewCustomer({ record, type: 'out' }),
              },
              {
                title: '查看片区',
                auth: quota_Import_lookItemArea,
                action: (text: any, record: any) => {
                  this.openModalViewArea({ record, type: 'out' })
                },
              },
            ],
            4
          ),
        },
      ],
      leftBtns: [
        uaaApp.canUse(CREATE_NEW_PLAN) && (
          <Button
            type="primary"
            style={{ marginRight: 10 }}
            onClick={() => {
              this.showAddPlanModal()
            }}
          >
            新增年度计划
          </Button>
        ),
         uaaApp.canUse(quota_Import_batchImportActual) && (
          <Button
            type="primary"
            style={{ marginRight: 10 }}
            onClick={() => {
              this.handBatchImportExcel()
            }}
          >
            批量导入实际配额
          </Button>
        ),
        uaaApp.canUse(EXPORT_QUOTA_LIST) && (
          <Button type="primary" style={{ marginRight: 10 }} onClick={this.exportCheckedRecord}>
            导出
          </Button>
        ),
      ],
      rightBtns: [
        uaaApp.canUse(IMPORT_QUPTA_LOGS) && (
          <Button type="default" style={{ marginRight: 10 }} onClick={this.showImportRecordModal}>
            导入记录
          </Button>
        ),
      ],
      tableProps: {
        footer: () => (
          <div>
            <span style={{ fontWeight: 'bold', fontSize: 14 }}>主要公式说明</span>
            <br />
            品牌公司计划（内、外）年度标准配额=所有经销商各阶段计划（内、外）标准配额之和 <br />
            品牌公司计划（内、外）实际配额=所有经销商各阶段计划（内、外）实际配额之和 <br />
            品牌公司计划（内、外）年度剩余配额=品牌公司计划（内、外）年度标准配额-品牌公司计划（内、外）年度实际配额
            <br />
          </div>
        ),
        bordered: true,
        scroll: { x: true },
        expandedRowRender: this.expandedRowRender,
        onExpand: this.onExpand,
      },
      loading: true,
      uploading: false,
      downloading: false,
      stageYearList: [],
      prodBarCodeList: [],
      customerTemplateType: 'MODULATION',
    }
  }

  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        {super.render()}
      </Spin>
    )
  }
  componentDidMount() {
    super.componentDidMount()
    this.getStageYearList()
    this.getProdBarList(this.filterForm.getFieldValue('brandCode'))
  }

  protected filterReset = (form: WrappedFormUtils) => {
    let defaultValues: any = {}
    _.forEach(this.state.conditions, (item: IUdFormItem) => {
      if (item.initialValue) {
        let key = _.isArray(item.id) ? item.id.join('|') : item.id
        defaultValues[key] = item.initialValue
      }
    })
    var conditions = _.merge({}, this.defaultQueryParams.conditions, defaultValues)
    this.handleSearch(conditions)
    this.getProdBarList(this.brandList[0].value)
  }

  private exportCheckedRecord = () => {
    let ids = this.state.selectedRowKeys
    if (ids.length === 0) {
      message.warn('请选择数据')
      return
    }
    http
      .get(quotaApis.exportCheckedRecord, { params: { ids: ids.join(',') }, responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFileXlsx(res.data, '客户年度配额数据')
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  private getProdBarList = (value: any) => {
    this.filterForm.setFieldsValue({ prodBarcode: undefined }, () => {
      this.setState({ prodBarCodeList: [] }, () => {
        http
          .get(quotaApis.getProdBarList, {
            params: { brandCode: value },
          })
          .then(res => {
            const { data = [] } = res
            const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
            this.setState({
              prodBarCodeList,
            })
          })
      })
    })
  }

  private getStageYearList = () => {
    http.get(comApis.GetQuotaAssessYearList).then(res => {
      const stageYearList = res.data?.map(({ year: value, name: title }) => ({ value: value + '', title })) || []
      this.setState({ stageYearList })
    })
  }

  private showImportRecordModal = () => {
    UdDrawer.open({
      title: '导入记录',
      width: '70%',
      footer: false,
      content: <ImportRecordModal brandList={this.brandList} stageYearList={this.state.stageYearList} />,
    })
  }

  private showImportExcel = (data: any) => {
    let title = ''
    const { modifyType } = data
    if (modifyType === 'QUOTACHANGE') {
      title = '客户标准配额'
    } else if (modifyType === 'ACTUAL') {
      title = '客户实际配额'
    } else {
      title = '客户配额调整'
    }
    UdDrawer.open({
      title: title,
      width: '40%',
      content: <ImportExcel data={data} refresh={this.query} modifyType={modifyType} />,
    })
  }

  private handBatchImportExcel = () => {
    let {brandCode} = this.queryParams.conditions
    let{stageYearList} = this.state
    let title = '批量导入实际配额'
    UdDrawer.open({
      title: title,
      width: '40%',
      content: <BatchImportExcel stageYearList={stageYearList}  brandCode={brandCode}  refresh={this.query} />,
    })
  }

  private showAddPlanModal = (record?: object) => {
    let title = record ? '编辑' : '新增'
    UdDrawer.open({
      title: `${title}计划`,
      width: '70%',
      content: (
        <PlanTable
          stageYearList={this.state.stageYearList}
          brandList={this.brandList}
          record={record}
          handQuery={this.query}
        />
      ),
    })
  }

  private openModalViewCustomer = ({ record, type }) => {
    let title = '查看客户'
    if (type === 'out') {
      title = `${record.stageYear}年-${record.prodBarname}-客户年度配额`
    } else {
      title = `${record.stageYear}年(${record.stageName})-${record.prodBarname}客户配额`
    }
    UdDrawer.open({
      title: `${title}详情`,
      width: '70%',
      content: <ViewCustomerModal record={record} type={type} title={title} />,
      footer: false,
    })
  }

  private openModalViewArea = ({ record, type }) => {
    let title = '查看片区'
    if (type === 'out') {
      title = `${record.stageYear}年-${record.prodBarname}-片区配额`
    } else {
      title = `${record.stageYear}年(${record.stageName})-${record.prodBarname}片区配额`
    }
    UdDrawer.open({
      title: `${title}详情`,
      width: '70%',
      content: <ViewAreaModal record={record} type={type} title={title} />,
      footer: false,
    })
  }

  private onExpand = (expanded, record) => {
    if (!expanded) return null
    localStorage.setItem('historyRecord', record.id)
    http.get(quotaApis.geteExpandedQuotaImportList, { params: { id: record.id } }).then(resp => {
      let value = { ...this.state.selectData }
      value[record.id] = resp.data
      this.setState({
        loading: false,
        selectData: value,
      })
    })
  }
  private expandedRowRender = (recode, index) => {
    const columns: IUdColumn<any>[] = [
      {
        title: '考核阶段',
        dataIndex: 'stageName',
        key: 'stageName',
        width: 150,
        render: (text, record) => {
          return (
            <Tooltip title={record.stageName}>
              <div style={{ width: '150px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.stageName}
              </div>
            </Tooltip>
          )
        },
      },
      { title: '配额品项', key: 'prodBarname', dataIndex: 'prodBarname', width: 200 },
      {
        title: '片区',
        dataIndex: 'belongAreaName',
        key: 'belongAreaName',
        width: 200,
        render: (text, record) => {
          return (
            <Tooltip title={record.belongAreaName}>
              <div style={{ width: '200px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                {record.belongAreaName}
              </div>
            </Tooltip>
          )
        },
      },
      { title: '考核年度', dataIndex: 'stageYear', key: 'stageYear', width: 100 },
      {
        title: '配额有效期',
        dataIndex: 'term',
        key: 'term',
        width: 190,
        render: (text, record) => {
          return record.stageBeginTime && record.stageEndTime ? `${record.stageBeginTime}-${record.stageEndTime}` : ''
        },
      },
      {
        title: '考核阶段标准配额',
        key: 'standardQuotaSumTitle',
        dataIndex: 'standardQuotaSumTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'standardQuotaSum',
            key: 'standardQuotaSum',
            width: 90,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'standardQuotaSumWay',
            key: 'standardQuotaSumWay',
            width: 90,
          },
        ],
      },
      {
        title: '考核阶段实际配额',
        key: 'actualQuotaSumTitle',
        dataIndex: 'actualQuotaSumTitle',
        align: 'center',
        children: [
          {
            title: '计划内',
            align: 'center',
            dataIndex: 'actualQuotaSum',
            key: 'actualQuotaSum',
            width: 90,
          },
          {
            title: '计划外',
            align: 'center',
            dataIndex: 'actualQuotaSumWay',
            key: 'actualQuotaSumWay',
            width: 90,
          },
        ],
      },
      {
        title: '状态',
        dataIndex: 'stageStatus',
        key: 'stageStatus',
        width: 140,
        render: (text, record, index) => {
          let stageStatus = {
            EXECUTED: '已执行',
            EXECUTION: '执行中',
            UNEXECUTED: '待执行',
          }
          return stageStatus[record.stageStatus]
        },
      },
      {
        title: '操作',
        minWidth: '200px',
        render: columnRenders.operate(
          [
            {
              title: '导入实际配额',
              auth: quota_Import_importActual,
              show: (text: any, record: any, index: number) => {
                if(record.isHis === 1) {
                  return false;
                }
                //已执行不显示
                if (record.stageStatus === 'EXECUTED') {
                  if (
                    ['GS100283', 'GS100300', 'GS100318', 'GS100276', 'GS100277', 'GS100285', 'BM100663'].includes(
                      record.brandCode
                    )
                  ) {
                    return true
                  }
                  return false
                }
                return true
              },
              action: (text: any, record: any) =>
                this.showImportExcel({ record, modifyType: 'ACTUAL', name: '客户实际配额模板' }),
            },
            {
              title: '导入配额调整',
              auth: quota_Import_importAdjust,
              show: (text: any, record: any, index: number) => {
                if(record.isHis === 1) {
                  return false;
                }
                //已执行与待执行不显示
                if (record.stageStatus === 'EXECUTED') {
                  return false
                }
                return true
              },
              action: (text: any, record: any) => this.showImportExcel({ record }),
            },
            {
              title: '查看客户',
              auth: quota_Import_lookCustom,
              action: (text: any, record: any) => this.openModalViewCustomer({ record, type: 'inside' }),
            },
            {
              title: '查看片区',
              auth: quota_Import_lookArea,
              action: (text: any, record: any) => this.openModalViewArea({ record, type: 'inside' }),
            },
          ],
          4
        ),
      },
    ]
    return (
      <Spin spinning={this.state.loading}>
        <UdTable columns={columns} bordered={true} dataSource={this.state.selectData[recode.id]} pagination={false} />
      </Spin>
    )
  }
}

interface QuotaImportListState extends IBaseListPageState {
  loading: boolean
  selectData: any
  uploading: boolean
  downloading: boolean
  stageYearList: any[]
  prodBarCodeList: any[]
  customerTemplateType?: string
  fileList: any[]
}

interface QuotaImportListProps extends IBaseListPageProps {}
